﻿using BgWorks.Common;
using BgWorks.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace BgWorks.Works
{

    public class DllWork : IWork
    {
        public void WorkThing(JobModel jobModel)
        {
            JobData model = jobModel.Data;
            try
            {
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ExtDll", model.DllName);
                if (File.Exists(path))
                {
                    Assembly ass;
                    Type type;
                    object obj;
                    //获取并加载DLL类库中的程序集
                    ass = Assembly.LoadFrom(path);
                    //获取类的类型：必须使用名称空间+类名称
                    type = ass.GetType(model.DllSpace);
                    //获取类的方法：方法名称
                    MethodInfo method1 = type.GetMethod(model.DllMethod);
                    //对获取的类进行创建实例。//必须使用名称空间+类名称
                    // obj = ass.CreateInstance(model.Sql);
                    obj = Activator.CreateInstance(type);
                    object[] objs = null;
                    if (!string.IsNullOrEmpty(model.Args))
                    {
                        objs = model.Args.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(c => (object)c).ToArray();
                    }
                    method1.Invoke(obj, objs);
                }
                else
                {
                    LogHelper.GetLog().Error("dll执行时，未找到执行文件：" + path);
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLog().Error(model.ToString() + "，dll执行异常：" + ex);
                throw new Exception("dll执行异常:" + ex);
            }
            LogHelper.GetLog().Error("执行dll任务..");
        }
    }
}
